package com.wf.course.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.utils.fileupload.Pinyin4j;
import com.utils.page.PageBean;
import com.wf.course.service.IAdInfoService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;
import com.wf.course.dao.IAdInfoMapper;
import com.wf.course.model.ad.AdInfo;
import com.wf.course.model.course.CourseInfo;

@Service
@Transactional(rollbackFor=Exception.class)
public class IAdInfoServiceImpl implements IAdInfoService{
	
	@Autowired
	private IAdInfoMapper mapper;

	@Override
	public void indexInfo(PageBean<AdInfo> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean));
		
	}

	@Override
	public void saveOrUpdateAdInfo(AdInfo adInfo,MultipartFile imgFile,MultipartFile h5File) {
		// TODO Auto-generated method stub
		
		//新增
		if (adInfo.getId() == null) {
			if (!imgFile.isEmpty()) {
				String imgUrl = "";
				try {
					imgUrl = OSSUtil.addFile(imgFile, "adInfo", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				adInfo.setImgUrl(imgUrl);;
			}
			
			//上传h5文件（只限.zip）
			if (h5File != null && h5File.getSize() > 2) {
				unpackZip(adInfo, h5File);
			}
			if(adInfo.getGoodsId()!=null&& adInfo.getAdType()==4){
				adInfo.setCourseId(adInfo.getGoodsId());
			}
			if(adInfo.getCardId()!=null&& adInfo.getAdType()==5){
				adInfo.setCourseId(adInfo.getCardId());
			}
			
			if(adInfo.getChapterId()!=null&& adInfo.getAdType()==6){
				adInfo.setCourseId(adInfo.getChapterId());
			}
			
			this.mapper.saveAdInfo(adInfo);
		//修改
		} else {
		
			if (imgFile.getSize() != 0) {
				AdInfo adInf = mapper.queryAdInfoById(adInfo.getId());
				try{
					if(StringUtils.isNotBlank(adInf.getImgUrl())){
						// 删除原来图片
						OSSUtil.delete(adInf.getImgUrl(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				// 上传
				String imgUrl = "";
				try {
					imgUrl = OSSUtil.addFile(imgFile, "adInfo", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				adInfo.setImgUrl(imgUrl);
			}
		
		
		//删除有H5页面 上传新的H5页面
		if (h5File != null && h5File.getSize() > 2) {
			if (adInfo.getH5Url() != null) {
				String[] h5Url = adInfo.getH5Url().split("/");
				String str = h5Url[h5Url.length - 2];
				File oldFile = new File(Constants.H5Pages + Constants.AdInfo + str);
				if (oldFile.exists()) {
					deleteFile(oldFile);
				}

			}
			unpackZip(adInfo, h5File);
		} else {
			adInfo.setH5Url(adInfo.getH5Url());
		}
		if(adInfo.getGoodsId()!=null & adInfo.getAdType()==4){
			adInfo.setCourseId(adInfo.getGoodsId());
		}
		if(adInfo.getCardId()!=null & adInfo.getAdType()==5){
			adInfo.setCourseId(adInfo.getCardId());
		}
		
		if(adInfo.getChapterId()!=null & adInfo.getAdType()==6){
			adInfo.setCourseId(adInfo.getChapterId());
		}
		
		this.mapper.updateAdInfo(adInfo);
	}
 }

	@Override
	public AdInfo queryAdInfoById(Integer id) {
		// TODO Auto-generated method stub
		return mapper.queryAdInfoById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(id);
		 
	}
 
	/**
	 * 上传，解压zip包
	 * 
	 * @param AdInfo
	 * @param file
	 */
	private void unpackZip(AdInfo adInfo, MultipartFile h5File) {
		String fileName = h5File.getOriginalFilename();
		File dir = new File(Constants.H5Pages + Constants.AdInfo);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File dest = new File(Constants.H5Pages + Constants.AdInfo + File.separator + fileName);
		ZipFile zipFile = null;
		try {
			h5File.transferTo(dest);

			BufferedInputStream bis = null;
			FileOutputStream fos = null;
			BufferedOutputStream bos = null;
			zipFile = new ZipFile(dest, "GBK");
			Enumeration<ZipEntry> zipEntries = zipFile.getEntries();
			File file, parentFile;
			ZipEntry entry;
			String fix = "";
			byte[] cache = new byte[1024];
			while (zipEntries.hasMoreElements()) {
				entry = (ZipEntry) zipEntries.nextElement();
				String pinyinEntry = Pinyin4j.getPinYin(entry.getName());
				if (entry.isDirectory()) {
					new File(Constants.H5Pages + Constants.AdInfo + pinyinEntry).mkdirs();
					continue;
				}
				bis = new BufferedInputStream(zipFile.getInputStream(entry));
				file = new File(Constants.H5Pages + Constants.AdInfo + pinyinEntry);
				if ("html".equals(pinyinEntry.substring(pinyinEntry.lastIndexOf(".") + 1, pinyinEntry.length()))
						&& file.getParent().indexOf("__MACOSX") == -1) {
					fix = pinyinEntry;
				}
				parentFile = file.getParentFile();
				if (parentFile != null && (!parentFile.exists())) {
					parentFile.mkdirs();
				}
				fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos, 1024);
				int readIndex = 0;
				while ((readIndex = bis.read(cache, 0, 1024)) != -1) {
					fos.write(cache, 0, readIndex);
				}
				bos.flush();
				bos.close();
				fos.close();
				bis.close();
			}
			adInfo.setH5Url(Constants.H5URL + Constants.AdInfo + fix);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				zipFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		File oldFile = new File(Constants.H5Pages + Constants.AdInfo + fileName);
		oldFile.delete();
	}

	/**
	 * 递归删除文件夹
	 * 
	 * @param file
	 */
	private void deleteFile(File file) {
		if (file.isFile() || file.list().length == 0) {
			file.delete();
		} else {
			File[] files = file.listFiles();
			for (File f : files) {
				deleteFile(f);// 递归删除每一个文件
				f.delete();// 删除该文件夹
			}
			file.delete();
		}
	}

	@Override
	public void AdInfoTop(Integer id) {
		// TODO Auto-generated method stub
		//获取所有的广告位
		List<AdInfo> list = mapper.queryAdInfo();
		int order = 2;
		for (int i = 0; i < list.size(); i++) {
			if (id != list.get(i).getId()) {
				list.get(i).setOrderNum(order);
				order ++;
			}else {
				list.get(i).setOrderNum(1);
			}
		}
		mapper.updateAdInfoBatch(list);
	}
	
}
